/*   **********************************************************************  **
 **   Copyright notice                                                       **
 **                                                                          **
 **   (c) 2009, Around(J2)ME				                                 **
 **   All rights reserved.                                                   **
 **                                                                          **
 **   This program and the accompanying materials are made available under   **
 **   the terms of the New BSD License which accompanies this    			 **
 **   distribution.											                 **
 **   A copy is found in the textfile LICENSE.txt							 **
 **                                                                          **
 **   This copyright notice MUST APPEAR in all copies of the file!           **
 **                                                                          **
 **   Main developers:                                                       **
 **     Juri Strumpflohner		http://blog.js-development.com	             **
 **		Matthias Braunhofer		http://matthias.jimdo.com                    **
 **                                                                          **
 **  **********************************************************************  */

package com.aroundj2me.controller;

import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.aroundj2me.model.ContinentName;
import com.aroundj2me.model.Place;
import com.aroundj2me.model.XMLManager;
import com.aroundj2me.utility.Constants;

/**
 * Servlet implementation class ApplicationController
 */
public class ApplicationController extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private final List<String> continents = Arrays.asList(new String[] {ContinentName.ASIA, ContinentName.AFRICA, ContinentName.NORTHAMERICA, ContinentName.SOUTHAMERICA, ContinentName.EUROPE, ContinentName.AUSTRALIA});
	private final String xmlPlacesFile = "/WEB-INF/places.xml";
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ApplicationController() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Servlet#init(ServletConfig)
	 */
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	private void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String continentParam = request.getParameter("continent");
		if (continentParam != null) {
			if (continents.contains(continentParam)) {
				//create instance of XMLManager to read the places for the requested continent 
				XMLManager manager = new XMLManager(continentParam);
				
				InputStream input = null;
				String responseXML = "";
				try {
					input = getServletContext().getResourceAsStream(xmlPlacesFile);
					List<Place> places = manager.readPlaces(input);
					responseXML = manager.encodePlacesToXML(places);
				} catch (Exception e) {
					responseXML = manager.encodeAlert("An error occurred on the server!", Constants.ALERT_ERROR);
				}
				
				close(input);
				
				response.setContentType("application/xml");
				response.setStatus(HttpServletResponse.SC_OK);
				response.setContentLength(responseXML.length());
				response.getWriter().println(responseXML);
				
				return;
			}
		}else{
			response.getWriter().println("<h1>Welcome</h1>The Around(J2)ME server is up and running.");		
		}
	}
	
	/**
	 * tries to close the InputStream
	 * @param input
	 */
	private void close(InputStream input) {
		if (input != null) {
			try {
				input.close();
			} catch (Exception e) {
				//ignore exception
			}
		}
	}
}
